package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    ShoppingCartService shoppingCartService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 1.处理各种业务异常（地址簿，购物车数据）
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook == null) throw new  AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        Long currentId = BaseContext.getCurrentId(); // 取得当前用户ID，用于查询当前用户购物车
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(ShoppingCart.builder().userId(currentId).build());
        if(shoppingCartList == null || shoppingCartList.size() == 0) throw new  AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);

        // 2.向订单表插入1条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setUserId(currentId);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insert(orders);

        // 3.订单明细表插入N条数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            System.out.println("shoppingCart:  " + shoppingCart);
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            System.out.println("orderDetail: " + orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailList);

        // 4.清空当前购物车
        shoppingCartMapper.deleteByUserId(currentId);

        // 5.封装 VO对象
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder().id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();

        return orderSubmitVO;
    }

    // 历史订单查询
    @Override
    public PageResult OrderList(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId()); // 查询谁的用户ID

        Page<Orders> orderList = orderMapper.pageQuery(ordersPageQueryDTO);

        // 根据订单号查询菜品详情

        List<OrderVO> list = new ArrayList();
       if(orderList != null && orderList.size() > 0){
           for (Orders orders : orderList) {
               Long number = orders.getId();  // 获取关联的订单ID
               List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(number); // 关联的获取订单细节

               OrderVO orderVO = new OrderVO();
               BeanUtils.copyProperties(orders, orderVO);

               orderVO.setOrderDetailList(orderDetail);

               list.add(orderVO);
           }
       }
        return new PageResult(orderList.getTotal(), list);
    }

    // 根据id查询订单详情
    @Override
    public OrderVO getOrderById(Long id) {
        Orders order =  orderMapper.getById(id);
        List<OrderDetail> list = orderDetailMapper.getByOrderId(id);

        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(list);

        // 把地址附上去
        orderVO.setAddress(getAddress(order.getAddressBookId()));

        return orderVO;
    }

    // 取消订单
    @Override
    public void cancel(Long id) {
//- 待支付和待接单状态下，用户可直接取消订单
//- 商家已接单状态下，用户取消订单需电话沟通商家
//- 派送中状态下，用户取消订单需电话沟通商家
//- 如果在待接单状态下取消订单，需要给用户退款
//- 取消订单后需要将订单状态修改为“已取消”
        Orders order = orderMapper.getById(id);
        if (order == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        Integer status = order.getStatus(); // 订单状态

        if (status > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        /*
        // 订单处于待接单状态下取消，需要进行退款
        if (ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    ordersDB.getNumber(), //商户订单号
                    ordersDB.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额

            //支付状态修改为 退款
            orders.setPayStatus(Orders.REFUND);
        }
         */

        // 更新订单状态、取消原因、取消时间
        order.setStatus(Orders.CANCELLED);
        order.setPayStatus(Orders.REFUND);
        order.setCancelReason("用户取消");
        order.setCancelTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    // 再来一单
    @Override
    public void repetition(Long id) {
        List<OrderDetail> detailList = orderDetailMapper.getByOrderId(id); // 获取菜品

        // 再把菜品或者套餐一一放入购物车
        if(detailList != null && detailList.size() > 0){
            for (OrderDetail orderDetail : detailList) {
                ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
                BeanUtils.copyProperties(orderDetail,shoppingCartDTO);

                shoppingCartService.addShoppingCart(shoppingCartDTO);
            }
        }
    }
    /************************商家管理端********************************/
    // 订单搜索

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        List<Orders> ordersList = page.getResult();

        if (!CollectionUtils.isEmpty(ordersList)) {
            for (Orders orders : ordersList) {
                // 将共同字段复制到OrderVO
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);



                orderVO.setAddress(getAddress(orders.getAddressBookId()));

                String orderDishes = getOrderDishesStr(orders);

                // 将订单菜品信息封装到orderVO中，并添加到orderVOList
                orderVO.setOrderDishes(orderDishes);

                orderVOList.add(orderVO);
            }
        }

        return new PageResult(page.getTotal(),orderVOList);
    }

    private String getAddress(Long addressBookId){
        AddressBook addressBook = addressBookMapper.getById(addressBookId);
        // 地址拼接
        String provinceName = addressBook.getProvinceName();
        String cityName = addressBook.getCityName();
        String districtName = addressBook.getDistrictName();
        String detail = addressBook.getDetail();
        return provinceName + " " + cityName +" " + districtName + " " + detail;
    }

    /**
     * 根据订单id获取菜品信息字符串
     *
     * @param orders
     * @return
     */
    private String getOrderDishesStr(Orders orders) {
        // 查询订单菜品详情信息（订单中的菜品和数量）
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        // 将每一条订单菜品信息拼接为字符串（格式：宫保鸡丁*3;）
        List<String> orderDishList = orderDetailList.stream().map(x -> {
            String orderDish = x.getName() + "*" + x.getNumber() + ";";
            return orderDish;
        }).collect(Collectors.toList());

        // 将该订单对应的所有菜品信息拼接在一起
        return String.join("", orderDishList);
    }

    // 各个状态的订单数量统计
    @Override
    public OrderStatisticsVO statistics() {
        // 首先把订单全部查出来
        //订单状态 1待付款 2待接单 3已接单(待派送) 4派送中 5已完成 6已取消 7退款
//        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
//        orderStatisticsVO.setConfirmed(0);
//        orderStatisticsVO.setDeliveryInProgress(0);
//        orderStatisticsVO.setToBeConfirmed(0);
//
//        List<Orders> ordersList = orderMapper.getAll();
//
//        for (Orders orders : ordersList) {
//            Integer status = orders.getStatus();
//            if(status == 2){
//                orderStatisticsVO.setToBeConfirmed(orderStatisticsVO.getToBeConfirmed() + 1);
//            }else if(status == 3){
//                orderStatisticsVO.setConfirmed(orderStatisticsVO.getConfirmed() + 1);
//            }else if(status == 4){
//                orderStatisticsVO.setDeliveryInProgress(orderStatisticsVO.getDeliveryInProgress() + 1);
//            }
//        }

        //订单状态 1待付款 2待接单 3已接单(待派送) 4派送中 5已完成 6已取消 7退款
        Integer TO_BE_CONFIRMED = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer CONFIRMED = orderMapper.countStatus(Orders.CONFIRMED);
        Integer DELIVERY_IN_PROGRESS = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 封装
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(TO_BE_CONFIRMED);
        orderStatisticsVO.setConfirmed(CONFIRMED);
        orderStatisticsVO.setDeliveryInProgress(DELIVERY_IN_PROGRESS);


        return orderStatisticsVO;
    }

    // 接单
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order = Orders
                .builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED).build();
        orderMapper.update(order);
    }

    // 拒单
    @Override
    public void rejection(OrdersRejectionDTO rejectionDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(rejectionDTO.getId());
            // 订单只有存在且状态为2（待接单）才可以拒单
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 退款就不写了
        Orders build = Orders.builder().id(rejectionDTO.getId())
                .rejectionReason(rejectionDTO.getRejectionReason())
                .status(Orders.CANCELLED)
                .cancelTime(LocalDateTime.now())
                .build();

        orderMapper.update(build);
    }

    // 取消订单

    @Override
    public void adminCancel(OrdersCancelDTO cancelDTO) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(cancelDTO.getId());

        //支付状态 申请退款


        // 管理端取消订单需要退款，根据订单id更新订单状态、取消原因、取消时间
        Orders orders = new Orders();
        orders.setId(cancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(cancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }
    // 派送订单

    @Override
    public void delivery(Long id) {
        Orders orders = orderMapper.getById(id);

        if (orders == null || !Objects.equals(orders.getStatus(), Orders.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders order = new Orders();
        orders.setId(id);
        // 更新订单状态,状态转为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO paymentDTO) {

        paySuccess(paymentDTO.getOrderNumber());

        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);

        // 通过websocket向客户端浏览器推送消息 type orderId content
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号:" + outTradeNo);

        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);

    }

    @Override
    public void reminder(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getById(id);
        // 校验订单是否存在
        if (ordersDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        HashMap map = new HashMap();
        map.put("type",2); // 1表示接单  2表示催单
        map.put("orderId",id);
        map.put("content",ordersDB.getNumber());
        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);
    }
}
















